package com.campuscarbooking.api.service.impl;

import com.campuscarbooking.api.dto.UserDTO;
import com.campuscarbooking.api.exception.AuthenticationException;
import com.campuscarbooking.api.model.User;
import com.campuscarbooking.api.repository.UserRepository;
import com.campuscarbooking.api.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AuthenticationException("用户未登录");
        }

        String userId = authentication.getName();
        return userRepository.findById(Long.valueOf(userId))
                .orElseThrow(() -> new AuthenticationException("用户不存在"));
    }

    @Override
    public UserDTO getCurrentUserDTO() {
        return UserDTO.fromEntity(getCurrentUser());
    }

    @Override
    @Transactional
    public UserDTO updateUser(UserDTO userDTO) {
        User user = getCurrentUser();

        if (userDTO.getNickname() != null) {
            user.setNickname(userDTO.getNickname());
        }

        if (userDTO.getAvatarUrl() != null) {
            user.setAvatarUrl(userDTO.getAvatarUrl());
        }

        if (userDTO.getGender() != null) {
            user.setGender(userDTO.getGender());
        }

        if (userDTO.getPhone() != null) {
            user.setPhone(userDTO.getPhone());
        }

        return UserDTO.fromEntity(userRepository.save(user));
    }
} 